﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.ytocargo.EntityFramework
{
    internal static class EFStartup
    {
        internal static string GetSchemaByConName(string conName)
        {
            if (string.IsNullOrWhiteSpace(conName))
            {
                throw new ArgumentNullException(nameof(conName));
            }

            var con = ConfigurationManager.ConnectionStrings[conName];
            if (con == null)
            {
                throw new InvalidOperationException($"Db connection not found:{conName}!");
            }
            if (string.IsNullOrWhiteSpace(con.ConnectionString))
            {
                throw new Exception($"ConnectionString { conName }is empty!");
            }

            var array = con.ConnectionString.Split(';');
            var user = array.Where(x => !string.IsNullOrWhiteSpace(x) && x.Contains("="))
                                .FirstOrDefault(y => y.Trim().ToLower().StartsWith("user"));

            if(user == null)
            {
                throw new Exception($"ConnectionString { conName }is invalid !");
            }
            array = user.Split('=');
            return array[1].Trim().ToUpper();
        }

        public static string SetTableName(string tableName)
        {
            var name = tableName.Replace("Ms", "Yto_");
            if (name.EndsWith("History"))
            {
                name = name.Replace("History", "His");
            }
            return name.ToUpper();
        }
    }
}
